/* eslint-disable indent */
/* eslint-disable no-debugger */
const path = require('path')
const fs = require('fs')
const minify = require('html-minifier').minify
const md5 = require('./md5')

const publicPath = path.join(__dirname, '../', 'json')
const readJSON = (fileName) => {
  const str = readFile(fileName)
  return JSON.parse(str)
}
const readTestFileDir = () => {
  return fs.readdirSync(path.join(publicPath, 'test'), 'utf8')
}
const readFile = (fileName) => {
  return fs.readFileSync(path.join(publicPath, fileName), 'utf8')
}

const writeFile = (fileName, content) => {
  return fs.writeFileSync(path.join(publicPath, fileName), content)
}

const buildId = () => {
  return Date.now()
}

const print = (obj) => {
  console.log(JSON.stringify(obj, null, 4))
}
const buildTestFileSave = (testObj = {}) => {
  let { name = '', dt, num } = testObj
  num = num > 9 ? num : ('0' + num)
  return [dt, num, name].join('-') + '.html'
}
const copy = (obj) => {
  return JSON.parse(JSON.stringify(obj))
}

/**
 * 根据文件名生成对应的题目
 * @param {string} filename
 */
const bTest = (filename) => {
  debugger
  const filePath = path.join(__dirname, '../originData', filename)
  console.log('生成题目....', filename)
  // const outPath = path.join(__dirname, "../testData/", filename)
  if (!fs.existsSync(filePath)) {
    console.log('文件找不到:' + filePath)
    throw new Error('文件找不到:' + filePath)
  }

  const tmlFile = '../tml/t.html'

  const lastModDate = fs.statSync(filePath).mtime.toISOString().substring(0, 10)
  // 1. 读入数据
  const data = copy(require(filePath))
  data.dt = lastModDate
  data.list.forEach(it => {
    const options = it.options
    it.ans = options.filter(item => item.isRight).map(item => md5.hexMd5(item.content))
    if (it.ans.length === 0) {
      console.log(it)
      throw new Error('没有设置答案')
    }
    it.options = options.map(item => item.content)
    it.type = it.ans.length > 1 ? '多选题' : '单选题'
  })
  // print(data)
  // fs.writeFileSync(outPath, JSON.stringify(data, null, 4))

  // 2. 读入模板
  let originHtml = fs.readFileSync(path.join(__dirname, tmlFile), 'utf8')

  // 3. 替换，填入数据
  originHtml = originHtml.replace(/const d=\{.*\}/, `const d=${JSON.stringify(data)}`)

  // 4. 文件加密
  // minifyJS
  const encodeHtml = minify(originHtml, {
    removeAttributeQuotes: true,
    removeComments: true,
    collapseWhitespace: true,
    minifyJS: { compress: { drop_console: false } },
    minifyCSS: true,
    sortClassName: true
  })
  // eslint-disable-next-line no-debugger
  // 5.写入
  const fileName = filename.replace('.json', '') + '.html'
  const _t = path.join(__dirname, '../files/', fileName)
  fs.writeFileSync(_t, encodeHtml)
  console.log('生成题目....', filename, 'OK')
}

/**
 * 删除之前的html文件
 */
const deletHtml = () => {
  const htmlPath = path.join(__dirname, '../files')
  const htmlArr = fs.readdirSync(htmlPath)
  htmlArr.forEach(it => {
    if (it.includes('.html')) {
      fs.unlinkSync(path.join(htmlPath, it))
    }
  })
}
/***
 * 生成主页
 */
const bIndex = () => {
  debugger
  // 删除之前的html
  deletHtml()

  const folderPath = path.join(__dirname, '../originData')
  const jsonArr = fs.readdirSync(folderPath)
  const categoryList = jsonArr.reduce((acc, cur) => {
    if (cur.split('-').length === 1) { return acc }
    const cate = cur.split('-')[0]

    if (acc[cate]) {
      acc[cate].push(cur)
    } else {
      acc[cate] = [cur]
    }
    return acc
  }, {})
  console.log('categoryList')

  const htmlPath = path.join(__dirname, '../files')
  const htmlArr = fs.readdirSync(htmlPath)
  const result = []
  jsonArr.filter(it => {
    return it.split('-').length > 1
  }).forEach(it => {
    const r = require(path.join(folderPath, it))
    r.fileName = it
    result.push(r)
    const htmlName = it.replace('.json', '')
    if (!htmlArr.includes(htmlName)) {
      bTest(it)
    }
  })
debugger
  const tmlFile = '../tml/index.html'
  // 1. 读入数据
  const data = {
    list: Object.keys(categoryList).map(it => {
      const o = {}
      o.category = it
      o.list = categoryList[it].map(i => {
        const file = result.find(it => it.fileName === i)
        const obj = {
          desc: file.desc,
          name: file.name + '[' + file.list.length + ']',
          fileLink: i.replace('.json', '.html')
        }
        return obj
      })
      return o
    })
  }
  print(data)

  // 2. 读入模板
  let originHtml = fs.readFileSync(path.join(__dirname, tmlFile), 'utf8')

  // 3. 替换，填入数据
  originHtml = originHtml.replace(/const d=\{.*\}/, `const d=${JSON.stringify(data)}`)

  // 4. 文件加密
  // minifyJS
  const encodeHtml = minify(originHtml, {
    removeAttributeQuotes: true,
    removeComments: true,
    collapseWhitespace: true,
    minifyJS: { compress: { drop_console: true } },
    minifyCSS: true,
    sortClassName: true
  })
  // eslint-disable-next-line no-debugger
  // 5.写入
  const _t = path.join(__dirname, '../files/', 'index.html')
  fs.writeFileSync(_t, encodeHtml)
}
// bIndex()
module.exports = {
  buildTestFileSave,
  readFile,
  writeFile,
  buildId,
  readJSON,
  readTestFileDir,
  bTest,
  bIndex
}
